package impl_v1.client;

import impl_v1.factory.FactoryImpl;
import impl_v1.server.AuctioningSystemServer;

import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.util.Scanner;

import model.AuctionInformation;
import model.Item;
import model.WinnerInformation;
import model.exception.InvalidAuctionIDException;
import model.exception.WrongKeyException;
import model.factory.Factory;
import model.server.SellerInterface;

public class SellerClient {

	public static void main(String[] args) {

		try {
			SellerInterface auctioningSystem = (SellerInterface) Naming
					.lookup("rmi://localhost/AuctioningSystemService");

			Factory factory = new FactoryImpl();

			boolean end = false;
			Scanner scanner = new Scanner(System.in);
			String choice;

			do {
				System.out.println("Choose:");
				System.out.println("1 - Create an auction");
				System.out.println("2 - Close an auction");
				System.out.println("3 - Quit");

				choice = scanner.nextLine();

				switch (choice) {
				case "1":
					System.out.println("-----------------");

					System.out.println("Title :");
					String title = scanner.nextLine();

					System.out.println("Description :");
					String description = scanner.nextLine();

					System.out.println("Starting price (int):");
					int startingPrice = scanner.nextInt();

					System.out.println("Reserve price (int):");
					int reservePrice = scanner.nextInt();
					scanner.nextLine();

					Item item = factory.newItem(title, description);

					AuctionInformation info = auctioningSystem.createAuction(
							item, startingPrice, reservePrice);

					System.out.println("The auction was created! Id is " + info.getAuctionID() + ", key is " + info.getKey());

					break;
				case "2":
					System.out.println("-----------------");

					try {
						System.out.println("AuctionID :");
						int auctionID = scanner.nextInt();

						System.out.println("Key :");

						int key = scanner.nextInt();
						scanner.nextLine();

						WinnerInformation winnerInformation = auctioningSystem.closeAuction(auctionID, key);

						if (winnerInformation == null) {
							System.out.println("Auction closed. The auction has no bidder.");
						} else {
							System.out.println("Auction closed. The winner is " + winnerInformation);
						}

					} catch (InvalidAuctionIDException e) {
						System.out.println("This auction doesn't exist!");
					} catch (WrongKeyException e) {
						System.out.println("Wrong key.");
					}

					break;
				case "3":
					end = true;
					break;
				default:
					System.out.println("Error !");
				}
			} while (!end);

			scanner.close();

		} catch (MalformedURLException | RemoteException | NotBoundException e) {
			System.err.println(AuctioningSystemServer.SERVER_REMOTE_EXCEPTION);
		}
	}
}
